/** @author hong */
class SSGameView extends V.GameView
{
    // // public static AllowReportChildren: Array<any> = ["SSGameEffectPanel"];
    /** 游戏背景图片 */
    public gameBg: eui.Image;
    // public menuButton: eui.Button;
    public gameEffectPanel: SSGameEffectPanel;
    public backMenuGroup: eui.Group;
    /** 设置按钮 */
    public settingBtn: eui.Button;
    /** 自己的操作面板 */
    public operateCardGroup: eui.Group;
    /** 重置按钮 */
    public btnReset: eui.Button;
    /** 确定按钮 */
    public btnOk: eui.Button;
    // // /** 帮助按钮 */
    // // public helpButton: eui.Button;
    /** 帮忙面板 */
    public helpView: eui.Scroller;
    public progressTimerGroup: eui.Group;
    public progressTimerLabel: eui.BitmapLabel;
    /** 选中牌的列表 */
    public onCardList: Array<any> = [];
    /** 定庄动画值 */
    public valueEffect: number = 0;
    /** 道选择框 */
    public sdao: eui.Panel;
    /** 删除道德选择1 */
    public rmcard0: eui.Image;
    /** 删除道德选择2 */
    public rmcard1: eui.Image;
    /** 删除道德选择3 */
    public rmcard2: eui.Image;

    /** 缓存的玩家自己手牌数据 */
    public cbCardData:any = null;   
    /** 牌的组合数量 */
    public cbGroupCount:number = 0; 
    /** 组合的牌型 */
    public cbCardType:any = null; 
    /** 组合的牌数据 */
    public cbGroupCard:number[][] = null;
    /** 是否正在播放结束动画 */
    public endPlay: boolean = false;
    /** 游戏结束数据 */
    public gameEnd:any;
    // // public data: SSGameSceneData = SSGameSceneData.getInstance();

    public constructor() 
    {
        super();
        this.MAX_PLAYER = 4;
        this.Res = DataConfig.ResConfig[DataConfig.KIND_ID_SSS];
        this.skinName = "SSGameSceneSkin"
    }

    protected childrenCreated(): void 
    {
        super.childrenCreated();
        // this.backButton.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onBackButton, this);
        this.gameBg.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouchGroup, this);
        this.helpView.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouchGroup, this);
        this.settingBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onSettingBtn, this);
        // this.menuButton.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onMenuButton, this);
        this.btnReset.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onBtnReset, this);
        this.btnOk.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onBtnOk, this);
        // this.helpButton.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onHelpButton, this);
        this.sdao.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onSdao, this);
        this.rmcard0.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onRmcard, this);
        this.rmcard1.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onRmcard, this);
        this.rmcard2.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onRmcard, this);
        // this.zhidaoBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onZhidaoBtn, this);
        //添加牌点击事件
        for (var i = 0; i < 13; i++) 
        {
            this["card" + i].addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onCard, this);
            this["card" + i].addEventListener(egret.TouchEvent.TOUCH_MOVE, this.onCard, this);
            this["card" + i].addEventListener(egret.TouchEvent.TOUCH_END, this.onCard, this);
        }
        //添加可选牌型按钮事件
        for(let i=0;i<4;i++){
            this["cardgp"+i].addEventListener(egret.TouchEvent.TOUCH_TAP, this.onCardGp, this);
        }
        //添加选指定类型牌按钮
        for(let i=1;i<9;i++){
            this["opBt"+i].addEventListener(egret.TouchEvent.TOUCH_TAP, this.onOpBt, this);
        }
        this.gameEffectPanel.gameView = this;
        //添加网络事件
        // how.EventManager.getInstance(null).addEventListener(CMDConfig.GET_SS_OPENCARD, this.onOpenCard, this);
        // how.EventManager.getInstance(null).addEventListener(CMDConfig.GET_SS_GAMEEND, this.onGameEnd, this);
        this.initGameView();
    }

    /** 收到网络消息 */
    public onNetData(s:number, d:any):void{
        switch(s){
            case 100:{ //游戏开始
                this.cbCardData = d.cbCardData;
                this.cbGroupCount = d.cbGroupCount;
                this.cbCardType = d.cbCardType;
                this.cbGroupCard = d.cbGroupCard;
                for (var i = 0; i < this.MAX_PLAYER; i++){
                    if (this.playerList[i].visible) this.gameEffectPanel.playCardEffect(i, d.cbCardData);
                }
                how.SoundManager.playEffect("nn_sendcard_mp3");
                // 设置时钟
                this.startProgressTimer(20);
                break;
            }case 101:{ //玩家组好牌了
                this.onOpenCard(d);
                break;
            }case 103:{ //游戏结束比牌
                this.onGameEnd(d);
                break;
            }
        }
    }

    // // public get resourceList(): Array<string> 
    // // {
    // //     return ["dzpk_cards", "ss_game"];
    // // }

    /** 玩家组好牌了 */
    public onOpenCard(data: any):void{
        // // data = data.data;
        let seatid = this.c2p(data.wOpenCardUser);
        if(seatid == 0){
            if(data.bOpenSuccess == 1){
                this["overCards" + seatid].visible = true;
                this.operateCardGroup.visible = false;
            }
        }else{
            this["playerCards" + seatid].visible = false;
            this["overCards" + seatid].visible = true;
        }
    }

    /** 显示自己的牌 */
    public showMyCard(cbCardData: any, isEffect: boolean): void 
    {
        for (var j = 0; j < 13; j++) 
        {
            if (!isEffect) 
            {
                this["card" + j].visible = true;
                this["card" + j].source = "card_" + cbCardData[j] + "_png";
            }
        }
        this.operateCardGroup.visible = true;
        this["baipei"].visible = true;
        for(let i=0;i<4;i++){
            if(i<this.cbGroupCount){
                this["cardgp"+i].visible = true;
                this["cardgp"+i].label = SSCardLogic.typeName[this.cbCardType[i][0]] + "   " + SSCardLogic.typeName[this.cbCardType[i][1]] + "   " + SSCardLogic.typeName[this.cbCardType[i][2]];
            } else this["cardgp"+i].visible = false;
        }
        this.reShowCard();
        this.testOpBt();
    }

    private bTouchCard:boolean = false;
    private bTouchImg:eui.Image = null;
    /** 点击扑克牌 */
    public onCard(event: egret.TouchEvent): void 
    {
        if(event.type == egret.TouchEvent.TOUCH_BEGIN){
            this.bTouchCard = true;
            this.bTouchImg = null;
        }else if(event.type == egret.TouchEvent.TOUCH_MOVE || event.type == egret.TouchEvent.TOUCH_END){
            if(this.bTouchImg == event.currentTarget) return;
        }
        var ta: eui.Image = event.currentTarget;
        this.bTouchImg = ta;
        var index = this.onCardList.indexOf(ta);
        if (index != -1) 
        {
            ta.y = ta.y + 20;
            this.onCardList.splice(index, 1);
        } 
        else
        {
            ta.y = ta.y - 20;
            this.onCardList.push(ta);
        }
        how.SoundManager.playEffect("nn_dealcard_mp3");
        this.showDao();
    }

    /** 显示道选择框 */
    private showDao():void{
        if(this.onCardList.length == 3 && this["scard0"].visible == false){
            this.sdao.visible = true;
            this.sdao.y = 14;
            this.sdao.height = 100;
            this.sdao.width = 182;
        }else if(this.onCardList.length == 5 && (this["scard3"].visible == false || this["scard8"].visible == false)){
            this.sdao.visible = true;
            this.sdao.y = 120;
            this.sdao.width = 276;
            this.sdao.height = 100;
            if(this["scard3"].visible == false && this["scard8"].visible == false){
                this.sdao.height = 208;
            }else if(this["scard8"].visible == false){
                this.sdao.y = 224;
            }
        }else{
            this.sdao.visible = false;
        }
    }

    /** 点击可选牌型选择 */
    public onCardGp(e: egret.TouchEvent):void{
        let gpi = parseInt(e.currentTarget.name);
        for(let i=0;i<13;i++){
            this["card"+i].visible = false;
            this["card"+i].y -= 20;
            this["scard"+i].visible = true;
            this["scard"+i].source = "card_" + this.cbGroupCard[gpi][i] + "_png";
        }
        this.sdao.visible = false;
        this.rmcard0.visible = this.rmcard1.visible = this.rmcard2.visible = true;
        this.reShowCard();
    }

    /** 检查牌型按钮 */
    public testOpBt():void{
        let cards = [];
        for(let i=0;i<13;i++){
            if(this["card" + i].visible == true){
                cards.push(parseInt(this["card" + i].source.substr(5)))
            }
        }
        let tps = SSCardLogic.getTypes(cards);
        for(let i=1;i<=SSCardLogic.type.T8;i++){
            if(tps[i]) this["opBt"+i].enabled = true;
            else this["opBt"+i].enabled = false;
        }
    }

    private lastOp:string;
    private lastV:number;
    /** 点击指定牌型选牌 */
    public onOpBt(e: egret.TouchEvent):void{
        if(e.currentTarget.name != this.lastOp){
            this.lastV = 0;
            this.lastOp = e.currentTarget.name;
        }
        let cards = [];
        for(let i=0;i<13;i++){
            if(this["card" + i].visible == true){
                cards.push(parseInt(this["card" + i].source.substr(5)))
            }
        }
        let cds = SSCardLogic.getTypeCards(SSCardLogic.type[this.lastOp], this.lastV, cards);
        if(cds.length == 0 && this.lastV != 0) cds = SSCardLogic.getTypeCards(SSCardLogic.type[this.lastOp], 0, cards);
        if(cds.length == 0) return;
        this.onCardList = [];
        for(let i=0;i<13;i++){
            if(this["card" + i].visible == true){
                let c = parseInt(this["card" + i].source.substr(5));
                if(cds.indexOf(c) == -1) this["card" + i].y = 12;
                else{
                    this["card" + i].y = 12 - 20;
                    this.onCardList.push(this["card" + i]);
                } 
            }
        }
        this.lastV = SSCardLogic.getCardValue(cds[0]);
        for(let i=0;i<cds.length;i++){
            if(SSCardLogic.getCardValue(cds[i]) < this.lastV) this.lastV = cds[i];
        }
        this.showDao();
    }

    /**点击的道选择*/
    public onSdao(event: egret.TouchEvent):void{
        //console.log("onSdao " + event.localY + " " + event.currentTarget.y);
        if(event.currentTarget.y == 14){
            for(let i=0;i<3;i++){
                this["scard" + i].visible = true;
                this["scard" + i].source = this.onCardList[i].source;
            }
            this.rmcard0.visible = true;
        }else if(event.currentTarget.y == 120 && event.localY < 100){
            for(let i=3;i<8;i++){
                this["scard" + i].visible = true;
                this["scard" + i].source = this.onCardList[i-3].source;
            }
            this.rmcard1.visible = true;
        }else{
            for(let i=8;i<13;i++){
                this["scard" + i].visible = true;
                this["scard" + i].source = this.onCardList[i-8].source;
            }
            this.rmcard2.visible = true;
        }
        this.sdao.visible = false;
        this.reShowCard();
    }

    /**重新显示牌列表*/
    private reShowCard():void{
        let x = 0;
        for(let i=0;i<13;i++){
            if(this["card"+i].y < 12){
                this["card"+i].visible = false;
            }else{
               this["card"+i].x = x;//console.log("card " + i + " " + x);
               x += 50; 
            }
        }
        this.onCardList = [];
        this.testOpBt();
        if(this["scard0"].visible == true && this["scard3"].visible == true && this["scard8"].visible == true){
            this.btnOk.visible = this.btnReset.visible = true;
        }else{
            this.btnOk.visible = this.btnReset.visible = false;
        }
    }
    /** 删除指定道的牌数据 */
    private onRmcard(event: egret.TouchEvent):void{
        let bg = parseInt(event.currentTarget.name), ed = 3;
        if(bg != 0) ed = bg + 5;
        for(;bg < ed;bg++){
            let sc = this["scard"+bg].source;
            for(let i=0;i<13;i++){
                if(this["card"+i].source == sc){
                    this["card"+i].visible = true;
                    this["card"+i].y = 12;
                }
            }
            this["scard"+bg].visible = false;
        }
        event.currentTarget.visible = false;
        let sc = this.onCardList;
        for(let i=0;i<sc.length;i++) sc[i].y = 12;
        this.reShowCard();
        for(let i=0;i<sc.length;i++) sc[i].y -= 20;
        this.onCardList = sc;
        this.showDao();
    }

    /** 点击重置按钮 */
    public onBtnReset(): void 
    {
        for(let i=0;i<13;i++){
            this["card"+i].visible = true;
            this["card"+i].y = 12;
            this["scard"+i].visible = false;
        }
        this.reShowCard();
        this.rmcard0.visible = this.rmcard1.visible = this.rmcard2.visible = false;
    }

    /** 点击确定按钮 */
    public onBtnOk(): void 
    {
        let cardlist = [];
        for(let i=0;i<13;i++){
            let snm = this["scard"+i].source.substr(5,2);
            cardlist.push(parseInt(snm));
        }
        WebSocketInstance.getHallSocket().send("9,1", cardlist);
    }

    /** 初始化桌面 */
    public initGameView(): void 
    {
        console.log("initGameView", new Date());
        this.operateCardGroup.visible = false;
        this.progressTimerGroup.visible = false;
        for(var i=0;i<this.MAX_PLAYER;i++){
            let panel:eui.Panel = this["overCards" + i];
            for(let j=0;j<13;j++){
                let img:eui.Image = <eui.Image>panel.getChildAt(j);
                img.source = this.getPoke(0);
            }
            if(i > 0) this["playerCards" + i].visible = false;
            else{
                let dp:eui.Group = <eui.Group>panel.getChildByName("cmpcard");
                dp.visible = false;
                for(let m=0;m<12;m++) dp.getChildAt(m).visible = false;
            } 
            panel.visible = false;
            this["player" + i].bankerAnimation.visible = false;
        }
        for (var i = 0; i < 13; i++)
        {
            this["card" + i].visible = false;
            this["card" + i].y = 12;
            this["scard" + i].visible = false;
        }
        this.btnReset.visible = this.btnOk.visible = false;
        this["baipei"].visible = false;
        this.rmcard0.visible = this.rmcard1.visible = this.rmcard2.visible = false;
        this.sdao.visible = false;
    }

    /** 按下菜单按钮 */
    // public onMenuButton(): void 
    // {
    //     this.backMenuGroup.visible = !this.backMenuGroup.visible;
    // }
    /** 按下返回按钮 */
    // public onBackButton(): void 
    // {
    //     how.EventManager.getInstance(null).removeEventListener(CMDConfig.GET_SS_OPENCARD, this.onOpenCard, this);
    //     how.EventManager.getInstance(null).removeEventListener(CMDConfig.GET_SS_GAMEEND, this.onGameEnd, this);
    //     this.backMenuGroup.visible = false;
    //     // // this.report("onBackButton");
    // }

    /** 按下设置按钮 */
    private onSettingBtn(): void 
    {
        this.backMenuGroup.visible = false;
        // // this.report(SSGameSceneModule.request.onSettingBtn);
    }

    /** 点击背景区域 */
    public onTouchGroup(): void 
    {
        this.backMenuGroup.visible = false;
        this.helpView.visible = false;
    }

    /** 按下帮助按钮 */
    public onHelpButton(): void 
    {
        this.backMenuGroup.visible = false;
        this.helpView.visible = true;
    }

    //开始倒计时
    public startProgressTimer(time = 10): void 
    {
        egret.Tween.removeTweens(this.progressTimerLabel);
        if (time < 0) 
        {
            return;
        }
        this.progressTimerLabel.text = time.toString();
        this.progressTimerLabel.alpha = 1;
        this.progressTimerGroup.visible = true;
        time--;
        if (time == 0) 
        {
            this.progressTimerGroup.visible = false;
        } 
        else 
        {
            this.progressTimerLabel.text = time.toString();
            egret.Tween.get(this.progressTimerLabel).wait(900).to({ alpha: 0 }, 100).call(this.startProgressTimer, this, [time]);
        }
    }

    //停止倒计时
    public stopProgressTimer(): void 
    {
        egret.Tween.removeTweens(this.progressTimerLabel);
        this.progressTimerGroup.visible = false;
    }

    /** 断线重连 */
    public onSyncData(data: any):void{
        if(D.App.table.gameStatus == 102){
            for(let i=0;i<data.cbPlayer.length;i++){
                if(data.cbPlayer[i] == 0) continue;
                if(i == D.App.userData.chairID){
                    if(data.cbChooseOver[i] == 1) this["overCards0"].visible = true;
                    else{
                        this.cbGroupCount = data.cbGroupCount;
                        this.cbGroupCard = data.cbGroupCard;
                        this.cbCardType = data.cbCardType;
                        this.showMyCard(data.cbHandCardData, false);
                    }
                }else{
                    if(data.cbChooseOver[i] == 1) this["overCards" + this.c2p(i)].visible = true;
                    else this["playerCards" + this.c2p(i)].visible = true;
                }
            }
        }
    }

    /** 牌打开 */
    public cardShowEnd(i:number):void{
        if(i == 13){
            this.endPlay = false;
            egret.setTimeout(function(){
                this.initGameView();
                WebSocketInstance.getHallSocket().send(CMDConfig.SEND_READY);
            },this,3000);
            let pm:eui.Panel = this["overCards0"];
            let ngp:eui.Group = <eui.Group>pm.getChildByName("newcard");
            for(let m=12;m>-1;m--){
                pm.addChildAt(ngp.getChildByName("cd"+m), 0)
            }
            pm.getChildByName("cardType").visible = false;
            return;
        }
        let cid = D.App.userData.chairID, ei = 0;
        let panel:eui.Panel = this["overCards" + this.c2p(this.gameEnd.wBankerUser)];
        let panelm:eui.Panel = this["overCards0"];
        let ngp:eui.Group = <eui.Group>panelm.getChildByName("newcard");
        let img:eui.Image;
        if(i == 0) ei = i + 3;
        else ei = i + 5;
        for(;i<ei;i++){
            img = <eui.Image>panelm.getChildByName("cd"+i);
            img.scaleX = 0.5;
            img.source = this.getPoke(this.gameEnd.cbCardData[cid][i]);
            ngp.addChild(img);
            egret.Tween.get(img).to({scaleX:1.0}, 800);
            //显示对家牌
            if(cid == this.gameEnd.wBankerUser){
                for(let j=0;j<this.MAX_PLAYER;j++){
                    if(j == cid || this.gameEnd.cbCardData[j][0] == 0) continue;
                    panel = this["overCards" + this.c2p(j)];
                    img = <eui.Image>panel.getChildAt(i);
                    img.source = this.getPoke(this.gameEnd.cbCardData[j][i]);
                }
            }else{
                img = <eui.Image>panel.getChildAt(i);
                img.source = this.getPoke(this.gameEnd.cbCardData[this.gameEnd.wBankerUser][i]);
            }
        }
        let gp:eui.Group = <eui.Group>panelm.getChildByName("cmpcard");
        if(!gp.visible) gp.visible = true;
        img = <eui.Image>panelm.getChildByName("cardType");
        if(!img.visible) img.visible = true;
        let bi = 0, dao = 0;
        if(ei == 8){
            bi = 4, dao = 1;
            img.y = 97;
        } else if(ei == 13) {
            bi = 8, dao = 2;
            img.y = 168;
        } else {
            img.y = 20;
        }
        let cty = this.gameEnd.cbCardType[cid][dao];
        img.anchorOffsetX = 0;
        img.rotation = 0;
        img.source = SSCardLogic.serverTypeSource[cty];
        img.x = 20;
        if(img.source == "ssGame.type8"){
            img.x = 0;
        }else if(img.source == "ssGame.type1" || img.source == "ssGame.type7"){
            img.anchorOffsetX = 113;
            img.rotation = -90;
        }
        gp.getChildAt(bi).visible = gp.getChildAt(bi+1).visible = true;
        let fimg:eui.BitmapLabel = <eui.BitmapLabel>gp.getChildAt(bi+2),fimg2:eui.BitmapLabel = <eui.BitmapLabel>gp.getChildAt(bi+3);
        fimg.visible = fimg2.visible = true;
        fimg2.text = "(+0)";
        if(this.gameEnd.lTypeScore[cid][dao] > 0) {
            fimg.font = "ssNum2_fnt";
            fimg.text = "+1";
            if(this.gameEnd.lTypeScore[cid][dao] > 1) fimg2.text = "(+"+this.gameEnd.lTypeScore[cid][dao]+")";
        } else {
            fimg.font = "ssNum3_fnt";
            fimg.text = "-1";
        }
        fimg = <eui.BitmapLabel>gp.getChildAt(14);
        let v = 0;
        for(let n=0;n<=dao;n++) v += this.gameEnd.lTypeScore[cid][n];
        if(dao == 2) v = this.gameEnd.lGameScore[cid];
        if(v < 0){
            fimg.font = "ssNum3_fnt";
            fimg.text = v.toString();
        }else{
            fimg.font = "ssNum2_fnt";
            fimg.text = "+" + v;
        }
        egret.Tween.get(this).wait(800).call(this.cardShowEnd, this, [ei]);
    }

    /** 当游戏结束 */
    public onGameEnd(data: any): void 
    {
        this.endPlay = true;
        this.gameEnd = data/* = data.data*/;
        console.log(">>> SSGameSceneView onGameEnd");
        let cid = D.App.userData.chairID;
        this["player"+this.c2p(data.wBankerUser)].playBankerEffect();
        this.stopProgressTimer();
        if(cid != data.wBankerUser){ //自己不是庄的时候显示其它人的牌
            for(let i=0;i<this.MAX_PLAYER;i++){
                if(i == cid || i == data.wBankerUser) continue;
                let panel:eui.Panel = this["overCards" + this.c2p(i)];
                for(let j=0;j<13;j++){
                    let img:eui.Image = <eui.Image>panel.getChildAt(j);
                    img.source = this.getPoke(data.cbCardData[i][j]);
                }
            }
        }
        this.cardShowEnd(0);
    }
    /** 获取牌贴图 */
    public getPoke(k):string{
        return "card_" + k + "_png";
    }
}